package application.handlers;

import application.RequestHandler;
import application.UserLoggedManager;
import contracts.requests.MessageRequest;
import contracts.responses.MessageResponse;
import contracts.responses.TabooResponse;
import domain.entities.ChatMessage;
import domain.entities.User;
import domain.services.ChatMessageDomainService;
import internal.UserLoggedInfo;
import io.netty.channel.Channel;
import network.websocket.WSServerSender;
import util.ChannelHelper;

/**
 * 消息处理器
 *
 * @author wyl
 */
public class MessageHandler extends RequestHandler<MessageRequest, MessageResponse> {
    @Override
    public MessageResponse handle(MessageRequest messageRequest, Channel requestChannel) {
        //获取发消息的用户的连接id
        String requestId = ChannelHelper.getConnId(requestChannel);
        //通过连接id获取发消息的用户
        UserLoggedInfo info = UserLoggedManager.getUserLoggedInfo(requestId);
        if (info == null) {
            return null;
        }
        if (info.getIsTaboo()) {
            WSServerSender.send(info.getConnId(), new TabooResponse("您已经被禁言,无法发送消息"));
            return null;
        }
        User u = info.getUser();
        if (u != null) {
            //消息持久化
            ChatMessage message = new ChatMessage(
                    messageRequest.content,
                    u.getId());
            ChatMessageDomainService.Instance.add(message);

            //构造响应对象
            MessageResponse resp = new MessageResponse(
                    u.getNickname(),
                    messageRequest.content);

            //向所有已经登录的用户发送消息
            UserLoggedManager.sendLoggedAll(resp);
        }

        //由于已经对自己发送完成所以不需要重复发送
        return null;
    }
}
